//
//  PMScreenDownView.m
//  Manager
//
//  Created by lvzhao on 2020/7/31.
//  Copyright © 2020 吕VV. All rights reserved.
//

#import "PMScreenDownView.h"
#import "LZOptionView.h"
#import "PMScreeningViewController.h"

@interface PMScreenDownView()<UIGestureRecognizerDelegate>

@property (nonatomic,strong)UIView *backgroundView; //
@property (nonatomic,copy) void(^cancelBlock) (id object);
@property (nonatomic,copy) void(^sureBlock)(id object);
@property (nonatomic,strong) UIButton *sureBtn;
@property (nonatomic,strong) UIButton *cancelBtn;

@property (nonatomic,strong) NSDictionary *dictionary;
@property (nonatomic,copy)NSString *cancel;
@property (nonatomic,copy)NSString *sure;
@end

@implementation PMScreenDownView
/**
 *  returns Alert.
 *  title NSString
 *  message NSString
 *  cancel NSString
 *  sure NSString
 *  dictionary @{};里面的参数自定义    key:subTitles||image||cancelTitle||sureTitle||pointString;
 *  cancelBlock & sureBlock 回调
 *  returns Alert.
 */
+ (void)showScreenAlertType:(LZAlertType)alertType cancel:(NSString *__nullable)cancel sure:(NSString *__nullable)sure objectDict:(NSDictionary *__nullable)dictionary cancelBlock:(void(^)(__nullable id object))cancelBlock sureBlock:(void(^)(__nullable id object))sureBlock{
    
    
    UIView * window = LZCurrentView;
    for (UIView * aView in window.subviews) {
          if ([aView isKindOfClass:[PMScreenDownView class]]){
              PMScreenDownView * screenView = (PMScreenDownView *)aView;
              [screenView show];
              return;
          }
      }
      PMScreenDownView *alertView = [[PMScreenDownView alloc] initWithFrame:CGRectMake(0, 0,K_SCREENWIDTH , K_SCREENHEIGHT) alertType:alertType cancel:cancel sure:sure objectDict:dictionary cancelBlock:cancelBlock sureBlock:sureBlock];
      [window addSubview:alertView];
      return;
}


- (void)show{
    self.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundView.frame = CGRectMake(0, 0, K_SCREENWIDTH,  self.backgroundView.height);
    } completion:^(BOOL finished) {
    }];
    
}

+ (void)dismiss{
    UIView * window = LZCurrentView;
    for (UIView * aView in window.subviews) {
        if ([aView isKindOfClass:[PMScreenDownView class]]){
            PMScreenDownView *screenView = (PMScreenDownView *)aView;
            [screenView.backgroundView removeAllSubviews];
            [screenView.backgroundView removeFromSuperview];
            [screenView removeAllSubviews];
            [screenView removeFromSuperview];
            screenView = nil;
            return;
        }
    }
}

///block 回调 AlertView
- (id)initWithFrame:(CGRect)frame alertType:(LZAlertType)alertType cancel:(NSString *)cancel sure:(NSString *)sure objectDict:(NSDictionary *)dictionary cancelBlock:(void(^)(id object))cancelBlock sureBlock:(void(^)(id object))sureBlock{
    
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColorHex(0x000000) colorWithAlphaComponent:0.5];
        self.cancelBlock = cancelBlock;
        self.sureBlock = sureBlock;
        self.dictionary = dictionary;
        self.cancel = cancel;
        self.sure = sure;
        
        [self setupView];
        
        switch (alertType) {
            case LZAlertTypeMerchantScreen:
                [self initMerchantScreenView];
                break;
                
            case LZAlertTypeTradeScreen:
                [self initTradeScreenView];
                break;
                
            default:
                break;
        }
        
    }
    return self;
}

#pragma mark - setupView
- (void) setupView{
    self.backgroundView = [[UIView alloc]init];
    self.backgroundView.backgroundColor = COLOR_nav;
    self.backgroundView.frame = CGRectZero;
    [self addSubview:self.backgroundView];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = COLOR_cellLine;
    [self.backgroundView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(-55);
        make.height.mas_equalTo(0.5);
        make.width.mas_equalTo(K_SCREENWIDTH);
    }];
    
    
    //确定
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.titleLabel.font = PingFangSC(17);
    [sureBtn setTitle:self.sure forState:UIControlStateNormal];
    [sureBtn setTitleColor:COLOR_nav forState:UIControlStateNormal];
    sureBtn.backgroundColor = COLOR_appColor;
    self.sureBtn = sureBtn;
    [self.backgroundView addSubview:sureBtn];
    
    //取消
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.titleLabel.font = PingFangSC(17);
    [cancelBtn setTitle:self.cancel forState:UIControlStateNormal];
    [cancelBtn setTitleColor:COLOR_appColor forState:UIControlStateNormal];
    cancelBtn.backgroundColor = UIColor.whiteColor;
    self.cancelBtn = cancelBtn;
    [self.backgroundView addSubview:cancelBtn];
    
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.mas_equalTo(0);
           make.width.mas_equalTo(K_SCREENWIDTH/2);
           make.height.mas_equalTo(55);
           make.bottom.mas_equalTo(0);
       }];
       
       
       [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
           make.right.mas_equalTo(0);
           make.width.mas_equalTo(K_SCREENWIDTH/2);
           make.height.mas_equalTo(55);
           make.bottom.mas_equalTo(0);
       }];
       
    
}


#pragma mark LZAlertTypeTradeScreen
- (void)initTradeScreenView{
    
    CGFloat btnHeight = 50;
    NSArray *subTitles = self.dictionary[@"subTitles"];
    NSArray *subSelectTitles = self.dictionary[@"subSelectTitles"];
    NSArray *placeholders = self.dictionary[@"placeholders"];
    NSInteger maxHeight = subTitles.count * btnHeight;

    self.backgroundView.frame = CGRectMake(0, -maxHeight, K_SCREENWIDTH, maxHeight + 100);

    NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] init];
    
    
    NSMutableArray *contenViews = [[NSMutableArray alloc] init];
    
    
    @weakify(self)
    for(int i = 0; i < subTitles.count; i++){
        
        UIView *contentView = [[UIView alloc] init];
        [self.backgroundView addSubview:contentView];
        contentView.frame = CGRectMake(0, i * btnHeight, self.backgroundView.width, btnHeight);
        
        UILabel *titleLab = [UILabel lz_labelWithText:subTitles[i] fontSize:PingFangSC(15) color:COLOR_textColor];
        [contentView addSubview:titleLab];
        CGFloat titleWidth = [titleLab.text lz_textWidthWithFontSize:titleLab.font withMaxHeight:21];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.width.mas_equalTo(titleWidth + 8);
            make.height.mas_equalTo(21);
            make.top.mas_equalTo(21);
        }];
        
        if([titleLab.text containsString:@"单号"]
           ||[titleLab.text containsString:@"关键字："]
           ||[titleLab.text containsString:@"收款人名称"]
           ||[titleLab.text containsString:@"收款人电话"]){
            UITextField *keyTextField = [[UITextField alloc] init];
            keyTextField.font = PingFangSC(15);
            keyTextField.cornerRadius = 6;
            keyTextField.bWidth = 0.5;
            keyTextField.bColor = COLOR_bColor;
            keyTextField.placeholder = placeholders[i];
            keyTextField.lz_placeholderColor = COLOR_placeholderColor;
            UIView *leftView = [UIView new];
            leftView.frame = CGRectMake(0, 0, 10, 35);
            keyTextField.leftView = leftView;
            //设置显示模式为永远显示(默认不显示)
            keyTextField.leftViewMode = UITextFieldViewModeAlways;
            [contentView addSubview:keyTextField];
            [keyTextField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(titleLab.mas_centerY);
                make.left.mas_equalTo(titleLab.mas_right);
                make.right.mas_equalTo(-15);
                make.height.mas_equalTo(34);
            }];
            
            
            [[keyTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
                if([titleLab.text containsString:@"收款人名称"]){
                    dataDictionary[@"nickname"] = x;

                } else if ([titleLab.text containsString:@"收款人电话"]){
                    dataDictionary[@"mobile"] = x;
                } else {
                    dataDictionary[@"key"] = x;
                }
                
            }];
            [contenViews addObject:keyTextField];
            
        } else if([titleLab.text containsString:@"时间"]){
            UIButton *timeBtn = [UIButton lz_buttonTitle:@"" titleColor:COLOR_placeholderColor fontSize:15];
            [timeBtn setTitle: [NSString stringWithFormat:@"%@",placeholders[i]] forState:UIControlStateNormal];
            timeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
            timeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [timeBtn setTitleColor:COLOR_textColor forState:UIControlStateSelected];
            timeBtn.cornerRadius = 6;
            timeBtn.bColor = COLOR_bColor;
            timeBtn.bWidth = 0.5;
            timeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
            [contentView addSubview:timeBtn];
            [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(titleLab.mas_centerY);
                make.left.mas_equalTo(titleLab.mas_right);
                make.right.mas_equalTo(-15);
                make.height.mas_equalTo(34);
            }];
            
            [[timeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                
                RACSubject *subject = [RACSubject subject];
                PMScreeningViewController *screeningVC = [[PMScreeningViewController alloc] init];
                screeningVC.pickerModel = PMDatePickerModelYMDHM;
                screeningVC.reloadSubject = subject;
                [LZTool.currentViewController.navigationController pushViewController:screeningVC animated:YES];
                [subject subscribeNext:^(id  _Nullable x) {
                    NSDictionary *dict = x;
                    [timeBtn setTitle:[NSString stringWithFormat:@"%@~%@",dict[@"startTime"],dict[@"endTime"]] forState:UIControlStateNormal];
                    timeBtn.selected = YES;
                    [dataDictionary addEntriesFromDictionary:dict];
                    
                }];
            }];
       
            [contenViews addObject:timeBtn];

        } else {
            LZOptionView *optionView = [[LZOptionView alloc] initWithFrame:CGRectMake(0, 0, 260, 34) dataSource:subSelectTitles[i]];
            optionView.placeholder = placeholders[i];
            [contentView addSubview:optionView];
            [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(titleLab.mas_centerY);
                make.left.mas_equalTo(titleLab.mas_right);
                make.right.mas_equalTo(-15);
                make.height.mas_equalTo(34);
            }];
            
            [optionView setSelectedBlock:^(LZOptionView * _Nonnull optionView, LZOptionModel * _Nonnull optionModel) {
                dataDictionary[optionModel.key] = optionModel.detail?:@"";
                
            }];
            [contenViews addObject:optionView];
        }
       
       
    }
    
    [[self.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {        
        for (int i = 0; i < contenViews.count; i++){
            UIView * subView = contenViews[i];
            if([subView isKindOfClass:[LZOptionView class]]){
                LZOptionView *optionView = (LZOptionView *)subView;
                optionView.placeholder = placeholders[i];
                optionView.titleColor = COLOR_placeholderColor;
            } else if([subView isKindOfClass:[UITextField class]]){
                
                UITextField *subTextField = (UITextField *)subView;
                subTextField.text = @"";
            } else if([subView isKindOfClass:[UIButton class]]){
                
                UIButton *subTimeBtn = (UIButton *)subView;
                subTimeBtn.selected = NO;
                [subTimeBtn setTitle:placeholders[i] forState:UIControlStateNormal];
            }
        }
        [dataDictionary removeAllObjects];
        if(self.cancelBlock){
            self.cancelBlock(dataDictionary);
        }
    }];
       
    [[self.sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        if(self.sureBlock){
            self.sureBlock(dataDictionary);
        }
        [self dismissAnimate:YES];
        
        [self endEditing:YES];
    }];
       
    [UIView animateWithDuration:0.2 animations:^{
        self.backgroundView.frame = CGRectMake(0, 0, K_SCREENWIDTH,  self.backgroundView.height);
    } completion:^(BOOL finished) {}];
        
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gestureRecognizerDismiss)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    
}
#pragma mark LZAlertTypeMerchantScreen
- (void)initMerchantScreenView{

         
     CGFloat btnHeight = 50;
     NSArray *subTitles = self.dictionary[@"subTitles"];
     NSArray *subSelectTitles = self.dictionary[@"subSelectTitles"];
     NSInteger maxHeight = subTitles.count * btnHeight;
     
     self.backgroundView.frame = CGRectMake(0, -maxHeight, K_SCREENWIDTH, maxHeight + 100);
     
    @weakify(self)
     for(int i = 0; i < subTitles.count; i++){
         
         UIView *contentView = [[UIView alloc] init];
         [self.backgroundView addSubview:contentView];
         contentView.frame = CGRectMake(0, i * btnHeight, self.backgroundView.width, btnHeight);
         
         UILabel *titleLab = [UILabel lz_labelWithText:subTitles[i] fontSize:PingFangSC(15) color:COLOR_textColor];
         [contentView addSubview:titleLab];
         CGFloat titleWidth = [titleLab.text lz_textWidthWithFontSize:titleLab.font withMaxHeight:21];
         [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
             make.left.mas_equalTo(15);
             make.width.mas_equalTo(titleWidth + 8);
             make.height.mas_equalTo(21);
             make.top.mas_equalTo(21);
         }];
         
         
         if([titleLab.text containsString:@"关键字"]){
             UITextField *keyTextField = [[UITextField alloc] init];
             keyTextField.font = PingFangSC(15);
             keyTextField.cornerRadius = 6;
             keyTextField.bWidth = 0.5;
             keyTextField.bColor = COLOR_bColor;
             keyTextField.placeholder = @"公司名称/商户号";
             UIView *leftView = [UIView new];
             leftView.frame = CGRectMake(0, 0, 10, 35);
             keyTextField.leftView = leftView;
             //设置显示模式为永远显示(默认不显示)
             keyTextField.leftViewMode = UITextFieldViewModeAlways;
             [contentView addSubview:keyTextField];
             [keyTextField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(titleLab.mas_centerY);
                make.left.mas_equalTo(titleLab.mas_right);
                make.right.mas_equalTo(-15);
                make.height.mas_equalTo(34);
             }];
             
             
         } else {
            LZOptionView *optionView = [[LZOptionView alloc] initWithFrame:CGRectMake(0, 0, 260, 34) dataSource:subSelectTitles[i]];
             optionView.title = subSelectTitles[i][0];
            [contentView addSubview:optionView];
            [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.mas_equalTo(titleLab.mas_centerY);
                make.left.mas_equalTo(titleLab.mas_right);
                make.right.mas_equalTo(-15);
                make.height.mas_equalTo(34);
            }];
         }
        
        
     }

     [[self.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
         @strongify(self)
         [self dismissAnimate:YES];
     }];
    
    [[self.sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
          @strongify(self)
          [self dismissAnimate:YES];
      }];
    
     [UIView animateWithDuration:0.2 animations:^{
         self.backgroundView.frame = CGRectMake(0, 0, K_SCREENWIDTH,  self.backgroundView.height);
     } completion:^(BOOL finished) {
         
     }];
     
     UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gestureRecognizerDismiss)];
     tap.delegate = self;
     [self addGestureRecognizer:tap];
 }

#pragma mark - 取消
- (void)dismissAnimate:(BOOL)animate{
    if(animate){
        [UIView animateWithDuration:0.3 animations:^{
            self.backgroundView.frame = CGRectMake(self.backgroundView.x, -self.backgroundView.height, self.backgroundView.width, self.backgroundView.height);
        } completion:^(BOOL finished) {
            self.hidden = YES;
        }];
    }
}

//手势
- (void)gestureRecognizerDismiss{
    [self dismissAnimate:YES];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{

    //如果是子视图 self ，设置无法接受 父视图 点击事件。
    if(touch.view == self){
         return YES;
     }
     return NO;
    
}


@end
